package org.luxor.commons.websocket.client;

import org.luxor.commons.websocket.annotation.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;

/**
 * 发送日志
 *
 * @author Mr.yan  @date 2021/8/3
 */
@Component
@WebSocketClient("ws://localhost:8080/websocket/console")
public class ConsoleClient {
    private static final Logger log = LoggerFactory.getLogger(ConsoleClient.class);

    private static Session session;

    /**
     * 发送日志消息
     *
     * @param message
     * @return void
     */
    public void sendText(String message) throws Exception {
        if (session != null) {
            session.getBasicRemote().sendText(message);
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("网络异常，响应客户端请求失败(sessionId:{})", session.getId(), error);
    }
}